<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- 
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License. 
-->
<html>
<head>
    <link type="text/css" rel="stylesheet" href="https://struts.apache.org/css/default.css">
    <style type="text/css">
        .dp-highlighter {
            width:95% !important;
        }
    </style>
    <style type="text/css">
        .footer {
            background-image:      url('https://cwiki.apache.org/confluence/images/border/border_bottom.gif');
            background-repeat:     repeat-x;
            background-position:   left top;
            padding-top:           4px;
            color:                 #666;
        }
    </style>
    <link href='https://struts.apache.org/highlighter/style/shCoreStruts.css' rel='stylesheet' type='text/css' />
    <link href='https://struts.apache.org/highlighter/style/shThemeStruts.css' rel='stylesheet' type='text/css' />
    <script src='https://struts.apache.org/highlighter/js/shCore.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushPlain.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushXml.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJava.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJScript.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushGroovy.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushBash.js' type='text/javascript'></script>
    <script type="text/javascript">
        SyntaxHighlighter.defaults['toolbar'] = false;
        SyntaxHighlighter.all();
    </script>
    <script type="text/javascript" language="javascript">
        var hide = null;
        var show = null;
        var children = null;

        function init() {
            /* Search form initialization */
            var form = document.forms['search'];
            if (form != null) {
                form.elements['domains'].value = location.hostname;
                form.elements['sitesearch'].value = location.hostname;
            }

            /* Children initialization */
            hide = document.getElementById('hide');
            show = document.getElementById('show');
            children = document.all != null ?
                    document.all['children'] :
                    document.getElementById('children');
            if (children != null) {
                children.style.display = 'none';
                show.style.display = 'inline';
                hide.style.display = 'none';
            }
        }

        function showChildren() {
            children.style.display = 'block';
            show.style.display = 'none';
            hide.style.display = 'inline';
        }

        function hideChildren() {
            children.style.display = 'none';
            show.style.display = 'inline';
            hide.style.display = 'none';
        }
    </script>
    <title>Exception Handling</title>
</head>
<body onload="init()">
<table border="0" cellpadding="2" cellspacing="0" width="100%">
    <tr class="topBar">
        <td align="left" valign="middle" class="topBarDiv" align="left" nowrap>
            &nbsp;<a href="home.html">Home</a>&nbsp;&gt;&nbsp;<a href="tutorials.html">Tutorials</a>&nbsp;&gt;&nbsp;<a href="getting-started.html">Getting Started</a>&nbsp;&gt;&nbsp;<a href="exception-handling.html">Exception Handling</a>
        </td>
        <td align="right" valign="middle" nowrap>
            <form name="search" action="https://www.google.com/search" method="get">
                <input type="hidden" name="ie" value="UTF-8" />
                <input type="hidden" name="oe" value="UTF-8" />
                <input type="hidden" name="domains" value="" />
                <input type="hidden" name="sitesearch" value="" />
                <input type="text" name="q" maxlength="255" value="" />
                <input type="submit" name="btnG" value="Google Search" />
            </form>
        </td>
    </tr>
</table>

<div id="PageContent">
    <div class="pageheader" style="padding: 6px 0px 0px 0px;">
        <!-- We'll enable this once we figure out how to access (and save) the logo resource -->
        <!--img src="/wiki/images/confluence_logo.gif" style="float: left; margin: 4px 4px 4px 10px;" border="0"-->
        <div style="margin: 0px 10px 0px 10px" class="smalltext">Apache Struts 2 Documentation</div>
        <div style="margin: 0px 10px 8px 10px"  class="pagetitle">Exception Handling</div>

        <div class="greynavbar" align="right" style="padding: 2px 10px; margin: 0px;">
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=14813967">
                <img src="https://cwiki.apache.org/confluence/images/icons/notep_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Edit Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=14813967">Edit Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">
                <img src="https://cwiki.apache.org/confluence/images/icons/browse_space.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Browse Space"></a>
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">Browse Space</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=14813967">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_page_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=14813967">Add Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=14813967">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_blogentry_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add News"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=14813967">Add News</a>
        </div>
    </div>

    <div class="pagecontent">
        <div class="wiki-content">
            <div id="ConfluenceContent"><div class="confluence-information-macro confluence-information-macro-information"><span class="aui-icon aui-icon-small aui-iconfont-info confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>The code for this tutorial, exception_handling, is available for checkout at <a shape="rect" class="external-link" href="https://github.com/apache/struts-examples" rel="nofollow">https://github.com/apache/struts-examples</a>.</p></div></div><h3 id="ExceptionHandling-Introduction">Introduction</h3><p>In this tutorial we'll explore how to enable the Struts 2 framework to handle any uncaught exceptions generated by a web application. Struts 2 provides robust exception handling, including the ability to automatically log any uncaught exceptions and redirect the user to a error web page.</p><div class="confluence-information-macro confluence-information-macro-tip"><span class="aui-icon aui-icon-small aui-iconfont-approve confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>The <a shape="rect" class="external-link" href="http://struts.apache.org/mail.html">Struts 2 user mailing list</a> is an excellent place to get help. If you are having a problem getting the tutorial example applications to work search the Struts 2 mailing list. If you don't find an answer to your problem, post a question on the mailing list.</p></div></div><h3 id="ExceptionHandling-GlobalExceptionHandling">Global Exception Handling</h3><p>Using the Struts 2 framework you can specify in the struts.xml how the framework should handle uncaught exceptions. The handling logic can apply to all actions (global exception handling) or to a specific action. Let's first discuss how to enable global exception handling.</p><p>To enable global exception handling you need to add two nodes to struts.xml: global-exception-mapping and global-results. For example examine struts.xml from the exception_handling project.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">  
   &lt;global-results&gt;
        &lt;result name="securityerror"&gt;/securityerror.jsp&lt;/result&gt;
  	&lt;result name="error"&gt;/error.jsp&lt;/result&gt;
   &lt;/global-results&gt;

   &lt;global-exception-mappings&gt;
	&lt;exception-mapping exception="org.apache.struts.register.exceptions.SecurityBreachException" result="securityerror" /&gt;
	 &lt;exception-mapping exception="java.lang.Exception" result="error" /&gt;
   &lt;/global-exception-mappings&gt;
  
</pre>
</div></div><p>The global exception mapping node tells the Struts 2 framework what to do if an uncaught exception of the type specified (or a child of that type) is thrown by the the application. For example if a SecurityBreachException is thrown but not caught, the Struts 2 Action class will return a result of "securityerror". All other uncaught exceptions will cause the Struts 2 Action class to return a result of "error".</p><p>The global results mapping node relates the result value to a specific view page. For example the result "securityerror" will cause the framework to redirect the user's browser to the securityerror.jsp view page.</p><h3 id="ExceptionHandling-ExceptionHandlingPerAction">Exception Handling Per Action</h3><p>If you need to handle an exception in a specific way for a certain action you can use the exception-mapping node within the action node.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">   &lt;action name="actionspecificexception" class="org.apache.struts.register.action.Register" method="throwSecurityException"&gt;
     &lt;exception-mapping exception="org.apache.struts.register.exceptions.SecurityBreachException" 
          result="login" /&gt;
      &lt;result&gt;/register.jsp&lt;/result&gt;
      &lt;result name="login"&gt;/login.jsp&lt;/result&gt;
   &lt;/action&gt;

</pre>
</div></div><p>The above action node from the example application's struts.xml file specifies that if method throwSecurityException throws an uncaught exception of type SecurityBreachException the Struts 2 framework should return a result of login. The login result will cause the user's browser to be redirected to login.jsp.</p><p>You can see that an action-specific exception mapping will take precedence if the same exception is also mapped globally.</p><h3 id="ExceptionHandling-LoggingExceptions">Logging Exceptions</h3><p>You can configure the Struts 2 framework to log any uncaught exceptions. To enable logging of the exceptions being handled by the Struts 2 framework you must specify some parameter values in struts.xml. If you examine the <a shape="rect" class="external-link" href="http://struts.apache.org/release/2.3.x/xwork-core/apidocs/com/opensymphony/xwork2/interceptor/ExceptionMappingInterceptor.html">ExceptionMappingInterceptor class API</a> there are three parameter values you can set to enable logging (logEnabled), the log level to use (logLevel), and the log category (logCategory) to specify in the log message.</p><p>To set these parameter values for all actions that use a specific stack of interceptors in a package include the following in struts.xml just after the opening package node.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">&lt;interceptors&gt;
  &lt;interceptor-stack name="appDefaultStack"&gt;
    &lt;interceptor-ref name="defaultStack"&gt;
     &lt;param name="exception.logEnabled"&gt;true&lt;/param&gt;
     &lt;param name="exception.logLevel"&gt;ERROR&lt;/param&gt;
    &lt;/interceptor-ref&gt;
 &lt;/interceptor-stack&gt;
&lt;/interceptors&gt;

&lt;default-interceptor-ref name="appDefaultStack" /&gt;

</pre>
</div></div><p>The above interceptors node configures a new stack of Struts 2 interceptors named appDefaultStack. This stack of interceptors is based upon the defaultStack of interceptors (which are the Struts 2 interceptors that execute by default whenever an Action class method is called by the Struts 2 framework).</p><p>The ExceptionMappingInterceptor is one of the Struts 2 interceptors that is part of the default stack. In the definition of the struts defaultStack, the ExceptionMappingInterceptor is given the name of exception. By specifying a param node with the name of exception.logEnabled and a value of true, I'm setting the logEnabled parameter of the ExceptionMappingInterceptor class to true.</p><p>Now when the application throws an uncaught exception, the Struts 2 framework will handle it and will also write an entry to the log that includes the stack trace. In the example above, I've set the level to log these exceptions to be ERROR.</p><p>In the example applications, the logging is just to the Servlet container's console (see the log4j.xml file for the log settings).</p><h3 id="ExceptionHandling-DisplayExceptionInformationInBrowser">Display Exception Information In Browser</h3><p>You can display information about the exception in the browser if you want by using s:property tags with a value of exception and exceptionStack. For example in error.jsp is this markup.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">   &lt;h4&gt;The application has malfunctioned.&lt;/h4&gt;

   &lt;p&gt;  Please contact technical support with the following information:&lt;/p&gt; 

   &lt;h4&gt;Exception Name: &lt;s:property value="exception" /&gt; &lt;/h4&gt;

   &lt;h4&gt;Exception Details: &lt;s:property value="exceptionStack" /&gt;&lt;/h4&gt; 

</pre>
</div></div><p>When the exception interceptor is triggered it adds to the fields available for display the exception message and the exception's stack trace.</p><h3 id="ExceptionHandling-Summary">Summary</h3><p>Struts 2 provides a easy to use configuration for handling uncaught exceptions and redirecting users to appropriate view pages. You can configure exception handling to be global for all actions or to just for a specific action. You can also enable the Struts 2 framework to log the uncaught exceptions.</p><h3 id="ExceptionHandling-UpNext">Up Next</h3><p>In our next tutorial we'll cover how to configure Struts 2 to make debugging a Struts 2 application simpler.</p><div class="table-wrap"><table class="confluenceTable"><tbody><tr><th colspan="1" rowspan="1" class="confluenceTh"><p>Next</p></th><td colspan="1" rowspan="1" class="confluenceTd"><p>Onward to <a shape="rect" href="debugging-struts.html">Debugging Struts</a></p></td></tr><tr><th colspan="1" rowspan="1" class="confluenceTh"><p>Prev</p></th><td colspan="1" rowspan="1" class="confluenceTd"><p>Return to <a shape="rect" href="message-resource-files.html">Message Resource Files</a></p></td></tr></tbody></table></div></div>
        </div>

                    <div class="tabletitle">
                Children
            <span class="smalltext" id="show" style="display: inline;">
              <a href="javascript:showChildren()">Show Children</a></span>
            <span class="smalltext" id="hide" style="display: none;">
              <a href="javascript:hideChildren()">Hide Children</a></span>
            </div>
            <div class="greybox" id="children" style="display: none;">
                                                    $page.link($child)
                    <span class="smalltext">(Apache Struts 2 Documentation)</span>
                    <br>
                            </div>
        
    </div>
</div>
<div class="footer">
    Generated by CXF SiteExporter
</div>
</body>
</html>
